import React, { Component } from "react";
import { View, Text, Image, StyleSheet, FlatList, TouchableWithoutFeedback } from "react-native";
import ChatInputBar from "../job/ChatInputBar";
import NetUtil from '../../net/net_util'
import PropTypes from "prop-types";
import Loading from "../../widget/Loading";
import Toast from "../../widget/Toast";
import img_arr from "../../util/img_arr";

let _this=this
class CommentItem extends Component{
  constructor(props) {
    super(props);
    this.state={
      inputPlaceholder:'说点什么'
    }
  }

  static propTypes={
    isReply:PropTypes.bool,
    comment:PropTypes.object,
    callback:PropTypes.func,
    replyback:PropTypes.func
  }

  static defaultProps={
    isReply:false,
    comment:{},
    callback:()=>{},
    replyback:()=>{}
  }

  render() {
    return (
      <View style={[styles.cell,this.props.style]}>
        <View style={styles.header}>
          <Image style={styles.portrait} source={{uri:this.props.comment.avatar}}></Image>
          <Text style={styles.nickName}>{this.props.comment.nickName}</Text>
          <View style={[styles.favorBox,{marginRight:14}]}>
            <Text style={{color:'#1C1C1C',fontSize:11,marginRight:5}}>{this.props.comment.likeNum}</Text>
            <TouchableWithoutFeedback onPress={()=>{this.props.callback(this.props.comment.id)}}>
              <Image style={{width:14,height:14}} source={this.props.comment.isLike==1?img_arr.icon_favor_selected:img_arr.icon_favor_normal}></Image>
            </TouchableWithoutFeedback>
          </View>
        </View>
        <View style={{paddingLeft:40}}>
          {this.props.isReply?(
            <Text style={styles.des}>{this.props.comment.pid!=this.props.comment.commentId?'回复':''}{this.props.comment.pid!=this.props.comment.commentId?(<Text style={styles.replyNickName}>{' '+this.props.comment.replyNickName+' '}</Text>):null}{this.props.comment.replyContent}</Text>
          ):(
            <Text style={styles.des}>{this.props.comment.content}</Text>
          )}
          <View style={styles.flex}>
            <Text style={styles.time}>{this.props.comment.displayTime}</Text>
            <Text style={[styles.time,{paddingHorizontal:3}]}>·</Text>
            {this.props.isReply?<Text style={styles.reply} onPress={this.props.replyback.bind(this,this.props.comment)}>回复</Text>:null}
          </View>
        </View>
        <View style={styles.line}></View>
      </View>
    )
  }
}

export default class CommentList extends Component{
  constructor(props) {
    super(props);
    this.chatInputBar=null;
    this.jobId='';
    this.trendId='';
    this.commentId='';
    this.pid='';
    this.userId='';
    this.state={
      commentId:'',
      comment:{},
      dataList:[]
    }
  }

  componentDidMount() {
    _this=this
    let params=this.props.route.params;
    this.commentId=params.commentId;
    this.setState({commentId:this.commentId})
    if(params.jobId){
      //需求
      this.jobId=params.jobId;
      this.getCommentDetail()
    }
    else {
      //动态
      this.trendId=params.trendId
      this.getDynamicCommentDetail()
    }
  }

  /*获取需求评论详情*/
  getCommentDetail(){
    let params={
      jobId:this.jobId,
      commentId:this.commentId
    }
    NetUtil.get('work/job/comment/detail',params,(res)=>{
      console.log(res)
      if(res.code==200){
        this.setState({comment:res.data,dataList:res.data.jobComments})
      }
    })
  }

  /*获取动态评论详情*/
  getDynamicCommentDetail(){
    let params={
      trendId:this.trendId,
      commentId:this.commentId
    }
    NetUtil.get('trend/comment/detail',params,(res)=>{
      console.log(res)
      if(res.code==200){
        this.setState({comment:res.data,dataList:res.data.trendComments})
      }
    })
  }

  /*点赞*/
  like(id){
    Loading.show()
    NetUtil.postFrom(this.jobId?'work/job/comment/like':'trend/comment/like',{'commentId':id},(res)=>{
      Loading.hide()
      if(res.code==200){
        if(this.jobId){
          this.getCommentDetail()
        }
        else {
          this.getDynamicCommentDetail()
        }
      }
    })
  }

  /*需求回复*/
  replyComment(text,pid,userId){
    let params={
      isReply:1,
      jobId:this.jobId,
      commentId:this.commentId,
      content:text,
      pId:pid?pid:this.state.comment.id,
      publishMid:userId?userId:this.state.comment.publishMid
    }
    console.log(params)
    Loading.show()
    NetUtil.postFrom('work/job/comment/create',params,(res)=>{
      Loading.hide()
      if(res.code==200){
        Toast.add('回复成功')
        this.getCommentDetail()
      }
      else {
        Toast.add(res.msg)
      }
      this.chatInputBar.closeInputBar()
    })
  }

  /*动态评论回复*/
  replyDynamicComment(text,pid,userId){
    let params={
      isReply:1,
      trendId:this.trendId,
      commentId:this.commentId,
      content:text,
      pId:pid?pid:this.state.comment.id,
      publishMid:userId?userId:this.state.comment.publishMid
    }
    console.log(params)
    Loading.show()
    NetUtil.postFrom('trend/comment/create',params,(res)=>{
      console.log(res)
      Loading.hide()
      if(res.code==200){
        Toast.add('回复成功')
        this.getDynamicCommentDetail()
      }
      else {
        Toast.add(res.msg)
      }
      this.chatInputBar.closeInputBar()
    })
  }

  /**点击回复*/
  _onBtnReply(comment){
    let placeholder=`回复${comment.nickName}`;
    this.pid=comment.id;
    this.userId=comment.publishMid;
    console.log(this.pid)
    this.setState({inputPlaceholder:placeholder});
    this.chatInputBar.openInputBar();
  }

  _onBtnPress(){
    this.chatInputBar.openInputBar();
  }

  _dismiss(){
    this.pid='';
    this.userId='';
    this.setState({inputPlaceholder:''});
  }

  /*发送消息*/
  _onSendMsg(text){
    this.setState({
      chatMsg:text,
    });
    if(this.jobId){
      this.replyComment(text,this.pid,this.userId)
    }
    else {
      this.replyDynamicComment(text,this.pid,this.userId)
    }
  }

  _renderItem=(info)=>{
    let item=info.item
    return <CommentItem comment={item}
                        commentId={this.state.commentId}
                        isReply={true}
                        replyback={(comment)=>{this._onBtnReply(comment)}}
                        callback={(id)=>{this.like(id)}}>
    </CommentItem>
  }
  _renderHeader=()=>{
    return (
      <View>
        <CommentItem comment={this.state.comment} callback={(id)=>{this.like(id)}}></CommentItem>
        <View style={{height:10,backgroundColor:'#F6F6F6'}}></View>
        <View style={styles.commentHeader}>
          <Text style={styles.commentTitle}>全部评论</Text>
        </View>
      </View>
    )
  }
  render(){
    return (
      <View style={{flex:1,backgroundColor:'#fff'}}>
        <View style={{flex:1,backgroundColor:'#F6F6F6'}}>
          <FlatList data={this.state.dataList}
                    renderItem={this._renderItem}
                    keyExtractor={(item)=>item.id}
                    ListHeaderComponent={this._renderHeader}>
          </FlatList>
        </View>
        <View style={styles.footer}>
          <TouchableWithoutFeedback onPress={this._onBtnPress.bind(this)}>
            <View style={styles.toolBar}>
              <Text style={styles.input}>说点什么...</Text>
            </View>
          </TouchableWithoutFeedback>
        </View>
        <ChatInputBar ref={s => this.chatInputBar = s}
                      isVisible={true}
                      placeholder={this.state.inputPlaceholder}
                      dismiss={()=>{}}
                      onSend={(text) => this._onSendMsg(text)}>
        </ChatInputBar>
        <Loading></Loading>
        <Toast></Toast>
      </View>
    )
  }
}

const styles=StyleSheet.create({
  cell:{
    paddingLeft:14,
    paddingTop:11,
    paddingBottom:20,
    backgroundColor:'#fff'
  },
  header:{
    flexDirection:'row',
    justifyContent:'space-between',
    alignItems:'center'
  },
  portrait:{
    width:30,
    height:30,
    borderRadius:15
  },
  nickName:{
    color:'#1C1C1C',
    fontSize:13,
    fontWeight:'500',
    marginLeft:10,
    flex:1
  },
  favorBox:{
    flexDirection: 'row',
    justifyContent: 'flex-end',
    alignItems: 'center'
  },
  des:{
    color:'#565656',
    marginTop:15,
    fontSize: 15
  },
  time:{
    color:'#C5C5C5',
    fontSize:10
  },
  line:{
    position:'absolute',
    bottom:0,
    height: 1,
    right:0,
    left:53,
    backgroundColor: '#F6F6F6'
  },
  commentHeader:{
    height:50,
    backgroundColor:'#fff',
    flexDirection:'row',
    justifyContent:'flex-start',
    alignItems:'center',
    borderBottomStyle:'solid',
    borderBottomColor:'#F6F6F6',
    borderBottomWidth:1
  },
  commentTitle:{
    color:'#959595',
    fontSize:15,
    marginLeft:15
  },

  footer:{
    height: 83,
    backgroundColor: '#fff',
  },
  toolBar:{
    marginHorizontal:15,
    marginTop:8,
    height:34,
    borderRadius:17,
    backgroundColor:'#F6F7F9'
  },
  input:{
    flex:1,
    lineHeight:34,
    color:'#9E9FA1',
    fontSize: 12,
    marginLeft: 15,
    marginRight:15
  },
  reply:{
    color:'#000000',
    fontSize:12
  },
  flex:{
    flexDirection:'row',
    justifyContent:'flex-start',
    alignItems:'center',
    marginTop: 10
  },
  replyNickName:{
    color:'#262626',
    fontSize:15,
    fontWeight:'500',
    paddingHorizontal:5
  }
})
